package ui.panel;

import cerebrum.common.ConfigPropertiesUtil;
import ui.factory.SingletonFactory;
import cerebrum.controller.wallpaper.WallpaperCerebrum;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.concurrent.Task;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Paint;
import javafx.stage.StageStyle;
import javafx.util.Duration;
import ui.util.Window;

import java.io.IOException;
import java.net.URL;

public class WelcomeStage extends Window {
    private static WelcomeStage instance = null;

    //调用单例工厂
    public static WelcomeStage getInstance() {
        if (instance == null) {
            instance = SingletonFactory.getWeakInstace(WelcomeStage.class);
        }
        return instance;
    }
    public WelcomeStage() throws IOException {
        URL resource = getClass().getResource("/fxml/Welcome.fxml");
        root = FXMLLoader.load(resource);

        //缩放图片到指定尺寸
        ((ImageView) $("welcome-image")).setFitWidth(450);
        ((ImageView) $("welcome-image")).setFitHeight(460);

        Scene scene = new Scene(root, 460, 450);
        scene.setFill(Paint.valueOf("#ffffff00"));
        initStyle(StageStyle.TRANSPARENT);
        setScene(scene);
        setTitle("IceoLogy壁纸");
        move();
        setIcon();
        setAlwaysOnTop(true);
        //逐渐变透明
        Timeline timeline = new Timeline();
        KeyFrame key = new KeyFrame(Duration.millis(4800),
                new KeyValue(root.opacityProperty(), 0.3));
        timeline.getKeyFrames().add(key);

        //显示完logo，进入下一步逻辑
        timeline.setOnFinished((ae) -> setUpShow(this));
        timeline.play();
    }

    //关闭此欢迎页面，显示设置页面
    private void setUpShow(WelcomeStage welcome) {
        //关闭欢迎页面
        welcome.close();
        //获取用户是否已经进行设置
        Boolean isSetUp = Boolean.valueOf(ConfigPropertiesUtil.get("is_user_set_up"));
        //没有设置就展开设置界面,设置了进入程序执行
        if (Boolean.TRUE.equals(isSetUp)) {
            new Thread(new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    //后台程序开始运行
                    WallpaperCerebrum.startRun(false);
                    return null;
                }

            }).start();
        } else {
            SetUpStage.getInstance().show();
        }
    }
}
